import json
import random
import time

import redis
import requests
from flask import Blueprint, send_file, make_response, redirect
from flask_restful import Resource
from ronglian_sms_sdk import SmsSDK
from tools.my_jwt import jj

from app import db
from tools.captcha.captcha import captcha
from tools.comm import sendMsg
from tools.myredis import r
from application.models.users.user import SfLogin

from application.models.users.user import *
from flask import Blueprint,request,jsonify
user_blue = Blueprint("userblue",__name__)
from captcha.image import ImageCaptcha

@user_blue.route('/text')
def get():
    return jsonify({'code':200,'msg':'mes'})



# 获取图片验证码
@user_blue.route("/getcode")
def getcode():
    #生成图片验证码 text文字  image图片流
    name, text, image = captcha.generate_captcha()
    # 从页面获取uuid作为redis key
    # data = request.json
    # uuid = data["uuid"]
    uuid = str(request.args.get("uuid"))
    print(text)

    # 存入redis
    r.str_add(uuid, text, 60)


    # 以流的方式生成验证码
    res = make_response(image)
    res.headers["Content-Type"] = "image/jpg"

    return res

@user_blue.route('/sendSmsCode',methods=['post'])
def sendSmsCode():
    data = request.data
    if data:
        # 获取3个参数
        data = json.loads(data)
        uuid = data['uuid']
        piccode = data['piccode']
        print(piccode,'>>>>>>>>>>>>>>>>')
        mobile = data['mobile']
        # redis中获取图片验证码
        value = r.str_get(uuid)
        # 对redis中获取的图片验证码解析
        value1 = value.decode()
        print(value1)
        # 如果图片验证码存在
        if value:
            # 将前端输入的验证码和图片验证码转为大小写 做对比
            if piccode.lower()==value1.lower():
                # 把redis里面存的手机号获取出来 然后赋值给mcode
                mcode = r.str_get(mobile)
                # 如果手机号存在
                if mcode:
                    return jsonify({'code':10012,'msg':'一分钟内不能重复发'})
                # 调用random生成随机数
                scode = random.randint(10000,99999)
                # 把容连云赋值到flag里面
                flag = sendMsg(mobile,scode)
                # 如果flag存在
                if flag:
                    # 就把手机号加入到redis里面 一分钟
                    r.str_add(mobile,scode,60)
                    # 判断完图形验证码之后 删除redis里面的图形验证码
                    r.del_key(uuid)
                    return jsonify({'code':200,'msg':'发送成功'})
                else:
                    return jsonify({'code':10013,'msg':'发送验证码错误'})
            else:
                return jsonify({'code':10011,'msg':'图片验证码错误'})

        else:
            return jsonify({'code':10010,'msg':'图片验证码不存在'})


@user_blue.route('/login',methods=['POST'])
# 注册登录接口
def login():
    # 获取前端返回的数据
    data = request.data
    # 如果存在
    if data:
        # 把获取到的data 转化json格式赋值到data里面
        data = json.loads(data)
        # 获取参数
        mcode = data['code']
        mobile = data['mobile']
        # 获取到redis里面存储的手机号
        code = r.str_get(mobile)
        print(code)
        print(mcode)
        # 如果手机号存在
        if code:
            #
            if int(code)==int(mcode):
                user = User.query.filter(User.mobile==mobile).first()
                if user:
                    r.del_key(mobile)
                else:
                    u = User(mobile=mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                    user = User.query.filter(User.mobile==mobile).first()
                # 用户信息生成jwt token
                token = jj.jwt_encode(data={'data':{'uid':user.id,'exp':int(time.time())}})
                return jsonify({'code':200,'token':token,'userid':user.id})
            else:
                return jsonify({'code':10021,'msg':'验证码错误'})
        else:
            return jsonify({'code':10020,'msg':''})





# 获取weibo地址

@user_blue.route('/sf_login')
def getwburl():
    client_id = "1167055427"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({"code":200,"url":url})

# weibo回调接口
@user_blue.route('/user/weiboCallback/')
def weiboCallback():
    # 获取code
    code = request.args.get("code")
    # 向access_token接口发送post请求
    data = {"client_id": '1167055427', "client_secret": "54c336d63782b0d25176a6c00f2ccb43",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 根据返回结果操作
    # 获取token和uid
    message = json.loads(res.text)
    token = message['access_token']
    uid = message['uid']
    # 查询数据库中是否存在，如果存在用户信息生成jwt token 返回
    sql = 'select user.id from user inner join sf_login on user.id=sf_login.userid where sf_login.uid=%s'%(uid)
    user = db.session.execute(sql)
    if user:
        for i in user:
            data = {'data':{'userid':i[0],'exp':int(time.time())}}
            token = jj.jwt_encode(data)
            return redirect("http://localhost:8080/#/updateToken?userid="+str(i[0]) + "&token=" + token)
    # 不存在跳转到vue绑定页面，token uid 传递过去
    return redirect("http://localhost:8080/#/banding?uid="+uid+"&token="+token)

# 绑定手机号
@user_blue.route('/bandMobile',methods=['POST'])
def bandMobile():
    data = json.loads(request.data)
    mobile = data['mobile']
    uid = data['uid']
    token = data['token']
    print(mobile,'>>>>>>>>>>>>>>>>>>>>>>>>>..')
    # 先查询用户表，如果手机号存在，获取userid,写入三方登录表，生成token返回
    user = User.query.filter(User.mobile==mobile).first()
    print(user)
    if not user:
        # 添加用户
        u = User(mobile=mobile,nikename=mobile)
        print(u)
        db.session.add(u)
        db.session.commit()
        # 获取用户信息
        user = User.query.filter(User.mobile==mobile).first()
    sfuser = SfLogin(userid=user.id, webfrom='wb', uid=uid, token=token)
    db.session.add(sfuser)
    db.session.commit()
    # 如果不存在，写入user表
    # 获取userid,写入三方登录表，生成token返回
    data = {'data':user.id,'exp':int(time.time())}
    token = jj.jwt_encode(data)
    return jsonify({'userid':str(user.id),'token':token})

# # 支付宝
import pymysql
from tools.comm import get_ali_object
@user_blue.route("/buy", methods=['POST'])
def test():
    # 获取参数
    data = json.loads(request.data)
    print(";;;;;;;;",data)
    userid = data["userid"]
    year = data["year"]
    money = 200
    tmoney = money * year
    # 生成订单
    order_no = str(int(time.time())) + str(userid)
    # 写入vip记录表
    viprecord = VipRecord(order_no=order_no, userid=userid, year=year, active_money=tmoney, status=1, money=money)
    db.session.add(viprecord)
    db.session.commit()

    # 支付，返回支付url
    pay = get_ali_object()
    # 生成支付的url
    query_params = pay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(1.00),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({"code":200, "url":pay_url})


# # 支付宝支付回调
# import datetime
# @user_blue.route("/user/callback")
# def callback():
#     # 接受参数
#     data = request.args
#     print(data)
#     # 字典推倒试
#     datames = {k:v for k,v in data.items()}
#     # 删除字典中key为sign的记录
#     sign = datames.pop('sign')
#     # 鉴权  订单号  流水号
#     pay = get_ali_object()
#     flag = pay.verify(datames,sign)
#     print(flag)
#     if flag == True:
#
#         # 支付宝流水号
#         transaction_no = datames["out_trade_no"]
#         # 订单号
#         order_no = datames['trade_no']
#
#         # try:
#         # 订单号更新订单表
#         record= VipRecord.query.filter(VipRecord.order_no==order_no).first()
#         # sql = "select * from vip_record where order_no = '%s'"%(order_no)
#         record.status=2
#         record.transaction_no=transaction_no
#         db.session.add(record)
#         # 更新用户表
#         User.query.filter(User.id == record.userid).update({"level":2})
#         # 更新vip表
#         vip= Vip.query.filter(Vip.userid==record.userid, Vip.status==1).first()
#         if vip is not None:
#             # 结束时间+购买年限
#             etime = vip.e_time.split("-")
#             year = int(etime[0])+int(record.year)
#             vip.e_time = year
#
#         else:
#             # nowyear = datetime.date.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%m:%s")
#             # etime = nowyear.split("-")
#             # etime[0] = int(etime[0])+int(record.year)
#             # print(etime)
#             # str ="-"
#             # retime = str.join(etime)
#             # print(retime)
#
#             year = 356*int(record.year)
#             retime = datetime.datetime.now()+datetime.timedelta(days=year)
#             vip = Vip(userid=record.userid, s_time=datetime.datetime.now(),e_time=retime)
#             db.session.add(vip)
#         db.session.commit()
#     else:
#         print("鉴权失败")
#     return "ok"






@user_blue.route("/user/callback")
def callback():
    # 接收参数，
    data = request.args
    datames = {k: v for k, v in data.items()}
    # 删除字典中key为sign的记录
    sign = datames.pop('sign')
    # 鉴权 订单号 流水号
    pay = get_ali_object()
    flag = pay.verify(datames, sign)

    if flag == True:
        # 支付宝流水号
        transaction_no = datames['trade_no']
        # 订单号
        order_no = datames['out_trade_no']
        # 订单号更新订单表
        try:
            record = VipRecord.query.filter(VipRecord.order_no == order_no).first()
            record.status = 2
            record.transaction_no = transaction_no
            db.session.add(record)
            # 更新用户表
            User.query.filter(User.id == record.userid).update({"level": 2})
            # # 更新vip表
            vip = Vip.query.filter(Vip.userid == record.userid, Vip.status == 1).first()
            print(vip)
            if vip is not None:
                # 结束时间+购买时间
                etime = vip.e_time.split("-")
                tyear = int(etime[0])+int(record.year)
                yearstr = "-"
                etime[0] = str(tyear)
                retime = yearstr.join(etime)
                vip.e_time = retime
                db.session.add(vip)
            else:
                nowyear = datetime.date.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%m:%s")
                etime = nowyear.split("-")
                tyear = int(etime[0])+int(record.year)
                etime[0] = str(tyear)
                yearstr = "-"
                retime = yearstr.join(etime)
                vip = Vip(userid = record.userid.userid,s_time=datetime.datetime.now(),e_time=retime)
                db.session.add(vip)
            db.session.commit()
        except:
            db.session.rollback()
    else:
        print("鉴权失败")
    return 'ok'
    # return redirect('http://localhost:8080/#/vip')








# 添加课程使用， 获取标签， 分类， 类别
@user_blue.route("/getTags")
def getTags():
    tags = Tags.query.all()
    tagslist = [{"id":i.id, "name":i.name} for i in tags]
    types = Ctype.query.all()
    typeslist = [{"id":i.id, "name":i.name} for i in types]
    ctype = CommentType.query.all()
    clist = [{"id":i.id, "name":i.name} for i in ctype]
    return jsonify({"code": 200, "tags":tagslist, "types":typeslist, "clist":clist})









from qiniu import Auth

@user_blue.route('/user/get_qntoken')
def get_qntoken():
    # 需要填写你的 Access Key 和 Secret Key
    access_key = 'f0cl5afOGWC6VZfto8rQVuIoItQDAqbpDLGffnvk'
    secret_key = 'AfsKB-PqOGkplPzJaMSak6VTpvLofvGKMUujhzVL'

    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    # 要上传的空间
    bucket_name = 'hhshu'

    # 3600为token过期时间，秒为单位。3600等于一小时
    token = q.upload_token(bucket_name)

    print(token)

    return jsonify({'code': 200, "token": token})

#

@user_blue.route("/user/addCourse", methods=['POST'])
def addCourse():
    # 获取参数
    data = json.loads(request.data)
    # 写入课程表
    course = Course(name=data['name'],url=data['url'],descrip=data['desc'],ctype=data['type'])
    res = db.session.add(course)
    # 获取新加的课程id
    scourse = Course.query.filter(Course.name == data['name']).first()
    # 写入课程标签表

    for i in data['tage']:
        sql = "insert into course_tag(courseid,tagid) values(%d,%d)"%(scourse.id,int(i))
        db.session.execute(sql)

    for i in data['ctype']:
        sql = "insert into course_cate(courseid,course_typeid) values(%d,%d)"%(scourse.id,int(i))
        db.session.execute(sql)
    db.session.commit()
    data = res.fetchone()
    print(data)
    return 'ok'



import math
# 分页
@user_blue.route('/getCourse')
def getCourse():
    # 获取参数page
    page = int(request.args.get('page'))
    # 获取上线、即将上线条件
    online = int(request.args.get('is_publish'))
    # 查询总条数
    total = Course.query.filter(Course.is_publish == online).count()
    # 定义每页显示多少条
    page_size = 2
    # 查询当前页记录
    start = math.ceil((page - 1) * page_size)
    # 获取排序字段
    orderpara = request.args.get('orderpara')
    if orderpara == 'new':
        course = Course.query.order_by(Course.create_time.desc()).filter(Course.is_publish == online).offset(
            start).limit(page_size).all()
    else:
        course = Course.query.order_by(Course.views.desc()).filter(Course.is_publish == online).offset(start).limit(
            page_size).all()
    list = [{"id": i.id, "name": i.name, "url": i.url, 'views': i.views} for i in course]
    # 返回结果
    return jsonify({'code': 200, "clist": list, "total": total, 'page_size': page_size})

# import math
#
# @user_blue.route("/getCourse")
# def getCourse():
#     # 获取参数page
#     page = request.args.get("page")
#     # 获取上线、即将上线条件
#     online = int(request.args.get('is_publish'))
#     # 查询总条数
#     total = Course.query.filter(Course.is_publish==online).count()
#     # 定义每页显示多少条
#     page_size = 2
#     # 查询当前页记录
#     start = math.ceil((page-1)*page_size)
#
#     # 获取排序字段
#     orderpara = request.args.get('orderpara')
#     if orderpara == 'new':
#         course = Course.query.order_by(Course.create_time.desc()).filter(Course.is_publish==online).offset(start).limit(page_size).all()
#     else:
#         course = Course.query.order_by(Course.views.desc()).filter(Course.is_publish == online).offset(start).limit(page_size).all()
#
#     list = [{"id":i.id, 'name':i.name, "url":i.url, "views":i.views} for i in course]
#     # 返回结果
#     return jsonify({"code":200, "clist":list, 'total':total, 'page_size':page_size})
#









# @user_blue.route('/getTags')
# def getTags():
#     tags = Tags.query.all()
#     tagslist = [{'id':i.id,'name':i.name}for i in tags]
#     ctype = Ctype.query.all()
#     ctypelist = [{'id':i.id,'name':i.name}for i in ctype]
#     course = CourseType.query.all()
#     courselist = [{'id':i.id,'name':i.name}for i in course]
#     return jsonify({'code':200,'tags':tagslist,'ctype':ctypelist,'course':courselist})



from db import db
@user_blue.route('/getid')
def getRoleResoure():
    id = request.args.get("id")
    print("id", id)
    if not id:
        return jsonify({'code':400,'msg':'数据不存在'})
    sql = "select * from course as c inner join course_tag as ct on ct.courseid=c.id where ct.tagid=" + id
    res = db.find_all(sql)
    print(res)
    return jsonify({"code": 200, 'data': res})



@user_blue.route('/getvip')
def getv():
    id = request.args.get("id")
    print(id)
    if not id:
        return jsonify({'code': 400, 'msg': '数据不存在'})
    # 免费
    if int(id) == 2:
        sql = "select * from course where is_vip=0"
        res = db.find_all(sql)
        return jsonify({'code': 200, 'getvip': res})
    # 会员
    if int(id) == 3:
        tsql = "select * from course where is_vip=1"
        tres = db.find_all(tsql)
        return jsonify({'code': 200, 'getvip': tres})
    # 全部
    else:
        qsql = "select * from course"
        qres = db.find_all(qsql)
        return jsonify({'code': 200, 'getvip': qres})


@user_blue.route('/getpub')
def GetIs_publish():
    id = request.args.get("id")
    print("id", id)
    if not id:
        return jsonify({'code':400,'msg':'数据不存在'})
    sql = "select * from course where is_publish=%d"%int(id)
    res = db.find_all(sql)
    print(res)
    return jsonify({"code": 200, 'data': res})




@user_blue.route('/hew_hot')
def Get_hew_hot():
    type = request.args.get("type")
    print(type)
    print(id)
    if not type:
        return jsonify({'code':400,'msg':'数据不存在'})
    if type == 'hew':
        sql = "select * from course order by create_time desc"
        res = db.find_all(sql)
        print(res)
        return jsonify({"code": 200, 'data': res})
    else:
        sql1 = 'select * from course order by views desc'
        ress = db.find_all(sql1)
        print(ress)
        return jsonify({"code": 200, 'data': ress})




